/**
 * # # THIS FILE IS PART OF drug-server PROJECT
 * # #
 * # MybatisPlusConfig.java - MybatisPlusConfig
 * #
 * # THIS PROGRAM IS OPENSOURCE SOFTWARE, IS LICENSED UNDER BSD
 * # YOU SHOULD HAVE RECEIVED A COPY OF WTFPL LICENSE
 * #
 * # Copyright (c) 2018 Ting Fan
 */
package com.cloudkinto.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.cloudkinto.common.constant.SysConstant;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Date;

@EnableTransactionManagement
@Configuration
@MapperScan("com.cloudkinto.dao")
public class MybatisPlusConfig implements MetaObjectHandler {
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // paginationInterceptor.setLimit(你的最大单页限制数量，默认 500 条，小于 0 如 -1 不受限制);
        return paginationInterceptor;
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        //填充为null的字段
        if (getFieldValByName("createDate", metaObject) == null) {
            setFieldValByName("createDate", new Date(), metaObject);
        }
        if (getFieldValByName("createTime", metaObject) == null) {
            setFieldValByName("createTime", new Date(), metaObject);
        }
        if (getFieldValByName("deleteFlag", metaObject) == null) {
            setFieldValByName("deleteFlag", SysConstant.DELETE_FLAG_FALSE, metaObject);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        //填充为null的字段
        if (getFieldValByName("updateDate", metaObject) == null) {
            setFieldValByName("updateDate", new Date(), metaObject);
        }
        if (getFieldValByName("updateTime", metaObject) == null) {
            setFieldValByName("updateTime", new Date(), metaObject);
        }
    }

    /**
     * 乐观锁
     */
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor() {
        return new OptimisticLockerInterceptor();
    }
}
